const { pool } = require('../config/db');
const llmService = require('./llmService');
const { downloadImage, extractFirstImageFromMarkdown } = require('../utils/fileUtils');
const config = require('../config/config');
const path = require('path');

/**
 * 武器装备处理服务
 */
class WeaponService {
  /**
   * 获取待处理的原始武器装备记录（支持分页）
   * @param {number} page - 页码（从1开始）
   * @param {number} pageSize - 每页数量
   * @returns {Promise<Object>} - 待处理的记录列表和总数
   */
  async getPendingRecords(page = 1, pageSize = 20) {
    try {
      // 获取总数
      const [countResult] = await pool.execute(
        'SELECT COUNT(*) as total FROM raw_weapons WHERE process_status = ?',
        ['pending']
      );
      const total = countResult[0].total;

      // 获取分页数据
      const offset = (page - 1) * pageSize;
      const [rows] = await pool.execute(
        'SELECT * FROM raw_weapons WHERE process_status = ? ORDER BY id DESC LIMIT ? OFFSET ?',
        ['pending', pageSize, offset]
      );

      return {
        data: rows,
        total: total,
        page: page,
        pageSize: pageSize,
        totalPages: Math.ceil(total / pageSize)
      };
    } catch (error) {
      console.error('获取待处理记录失败:', error.message);
      throw error;
    }
  }

  /**
   * 获取待处理记录（兼容旧接口）
   * @param {number} limit - 获取数量
   * @returns {Promise<Array>} - 待处理的记录列表
   */
  async getPendingRecordsList(limit = 10) {
    try {
      const [rows] = await pool.execute(
        'SELECT * FROM raw_weapons WHERE process_status = ? ORDER BY id DESC LIMIT ?',
        ['pending', limit]
      );
      return rows;
    } catch (error) {
      console.error('获取待处理记录失败:', error.message);
      throw error;
    }
  }

  /**
   * 更新原始记录的处理状态
   * @param {number} id - 记录ID
   * @param {string} status - 状态
   * @param {string} errorMsg - 错误信息（可选）
   */
  async updateProcessStatus(id, status, errorMsg = null) {
    try {
      const sql = `
        UPDATE raw_weapons 
        SET process_status = ?, process_time = NOW(), process_error = ?
        WHERE id = ?
      `;
      await pool.execute(sql, [status, errorMsg, id]);
    } catch (error) {
      console.error('更新处理状态失败:', error.message);
      throw error;
    }
  }

  /**
   * 保存处理后的武器装备基本信息
   * @param {number} rawWeaponId - 原始武器装备ID
   * @param {Object} basicInfo - 基本信息数据
   */
  async saveBasicInfo(rawWeaponId, basicInfo) {
    try {
      const sql = `
        INSERT INTO processed_weapons (
          raw_weapon_id, origin_country, category, chinese_name, english_name,
          chinese_intro, english_intro, thumbnail, contractor, service_time,
          development_background, construction_history, service_history,
          structural_features, equipment, power_system, status, data_source
        ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
      `;

      await pool.execute(sql, [
        rawWeaponId,
        basicInfo.origin_country || null,
        basicInfo.category || null,
        basicInfo.chinese_name || null,
        basicInfo.english_name || null,
        basicInfo.chinese_intro || null,
        basicInfo.english_intro || null,
        basicInfo.thumbnail || null,
        basicInfo.contractor || null,
        basicInfo.service_time || null,
        basicInfo.development_background || null,
        basicInfo.construction_history || null,
        basicInfo.service_history || null,
        basicInfo.structural_features || null,
        basicInfo.equipment || null,
        basicInfo.power_system || null,
        basicInfo.status || null,
        basicInfo.data_source || null
      ]);
    } catch (error) {
      console.error('保存基本信息失败:', error.message);
      throw error;
    }
  }

  /**
   * 递归保存战技指标（支持树形结构）
   * @param {number} rawWeaponId - 原始装备ID
   * @param {Array} specifications - 战技指标数组
   * @param {number|null} parentId - 父级ID
   * @param {number} level - 层级深度
   * @returns {Promise<number>} - 返回保存的节点总数
   */
  async saveSpecificationsRecursive(rawWeaponId, specifications, parentId = null, level = 1) {
    let totalCount = 0;

    for (let i = 0; i < specifications.length; i++) {
      const spec = specifications[i];
      const nodeType = spec.node_type || 'indicator';
      
      // 插入当前节点
      const [result] = await pool.execute(
        `INSERT INTO weapon_specifications 
        (raw_weapon_id, parent_id, level, node_type, indicator_chinese, indicator_english, 
         indicator_value, sort_order) 
        VALUES (?, ?, ?, ?, ?, ?, ?, ?)`,
        [
          rawWeaponId,
          parentId,
          level,
          nodeType,
          spec.indicator_chinese || null,
          spec.indicator_english || null,
          spec.indicator_value || null,
          i
        ]
      );

      const currentId = result.insertId;
      totalCount++;

      // 如果有子节点，递归保存
      if (spec.children && Array.isArray(spec.children) && spec.children.length > 0) {
        const childCount = await this.saveSpecificationsRecursive(
          rawWeaponId,
          spec.children,
          currentId,
          level + 1
        );
        totalCount += childCount;
      }
    }

    return totalCount;
  }

  /**
   * 保存战技指标
   * @param {number} rawWeaponId - 原始武器装备ID
   * @param {Array} specifications - 战技指标数组（树形结构）
   */
  async saveSpecifications(rawWeaponId, specifications) {
    try {
      if (!specifications || specifications.length === 0) {
        console.log('  - 没有战技指标需要保存');
        return;
      }

      // 先删除旧数据
      await pool.execute(
        'DELETE FROM weapon_specifications WHERE raw_weapon_id = ?',
        [rawWeaponId]
      );

      // 递归保存树形数据
      const totalCount = await this.saveSpecificationsRecursive(rawWeaponId, specifications);
      console.log(`  - 保存了 ${totalCount} 条战技指标（含 ${specifications.length} 个顶级节点）`);
    } catch (error) {
      console.error('保存战技指标失败:', error.message);
      throw error;
    }
  }

  /**
   * 保存使用用户信息
   * @param {number} rawWeaponId - 原始武器装备ID
   * @param {Array} users - 使用用户数组
   */
  async saveUsers(rawWeaponId, users) {
    try {
      if (!users || users.length === 0) {
        console.log('  - 没有使用用户需要保存');
        return;
      }

      const sql = `
        INSERT INTO weapon_users (
          raw_weapon_id, country, variant, operator_chinese,
          operator_english, operator_intro, order_quantity
        ) VALUES (?, ?, ?, ?, ?, ?, ?)
      `;

      // 批量插入
      for (const user of users) {
        await pool.execute(sql, [
          rawWeaponId,
          user.country || null,
          user.variant || null,
          user.operator_chinese || null,
          user.operator_english || null,
          user.operator_intro || null,
          user.order_quantity || null
        ]);
      }

      console.log(`  - 保存了 ${users.length} 条使用用户信息`);
    } catch (error) {
      console.error('保存使用用户失败:', error.message);
      throw error;
    }
  }

  /**
   * 处理单条武器装备记录
   * @param {Object} record - 原始武器装备记录
   * @returns {Promise<Object>} - 处理结果
   */
  async processSingleRecord(record) {
    try {
      console.log(`开始处理装备: ${record.name} (ID: ${record.id})`);

      // 更新状态为处理中
      await this.updateProcessStatus(record.id, 'processing');

      // 1. 从Markdown介绍中提取第一张图片URL
      console.log('- 提取缩略图URL...');
      const thumbnailUrl = extractFirstImageFromMarkdown(record.description);
      if (thumbnailUrl) {
        console.log(`  找到图片: ${thumbnailUrl.substring(0, 80)}...`);
      } else {
        console.log('  未找到图片');
      }

      // 2. 下载缩略图
      let thumbnailPath = null;
      if (thumbnailUrl) {
        try {
          console.log('- 下载缩略图...');
          const thumbnailDir = path.resolve(config.upload.uploadDir, 'thumbnails');
          thumbnailPath = await downloadImage(thumbnailUrl, thumbnailDir, 'uploads/thumbnails/');
          if (thumbnailPath) {
            console.log(`  ✓ 缩略图已保存: ${thumbnailPath}`);
          } else {
            console.log('  ⚠ 缩略图下载失败');
          }
        } catch (error) {
          console.warn('  ⚠ 下载缩略图失败:', error.message);
          thumbnailPath = null;
        }
      }

      // 3. 调用LLM提取信息
      console.log('- 调用LLM提取装备信息...');
      const context = { name: record.name };
      const extractResult = await llmService.extractWeaponInfo(record.description || '', context);

      if (!extractResult.success || !extractResult.data) {
        throw new Error('LLM提取失败或返回数据为空');
      }

      const { basic_info, specifications, users } = extractResult.data;

      // 4. 将下载的缩略图路径添加到基本信息中
      if (thumbnailPath) {
        basic_info.thumbnail = thumbnailPath;
      }

      // 5. 保存基本信息
      console.log('- 保存基本信息...');
      await this.saveBasicInfo(record.id, basic_info || {});

      // 6. 保存战技指标
      console.log('- 保存战技指标...');
      await this.saveSpecifications(record.id, specifications || []);

      // 7. 保存使用用户
      console.log('- 保存使用用户...');
      await this.saveUsers(record.id, users || []);

      // 8. 更新原始记录状态为已完成
      await this.updateProcessStatus(record.id, 'completed');

      console.log(`✓ 处理完成: ${record.name}`);

      return {
        success: true,
        recordId: record.id,
        name: record.name
      };
    } catch (error) {
      console.error(`✗ 处理失败: ${record.name}`, error.message);

      // 更新状态为失败
      await this.updateProcessStatus(record.id, 'failed', error.message);

      return {
        success: false,
        recordId: record.id,
        name: record.name,
        error: error.message
      };
    }
  }

  /**
   * 批量处理武器装备记录
   * @param {number} batchSize - 每批处理数量
   * @returns {Promise<Object>} - 处理结果统计
   */
  async processBatch(batchSize = 10) {
    try {
      console.log(`\n========== 开始批量处理 (批次大小: ${batchSize}) ==========\n`);

      // 获取待处理记录
      const records = await this.getPendingRecordsList(batchSize);

      if (records.length === 0) {
        console.log('没有待处理的记录');
        return {
          success: true,
          message: '没有待处理的记录',
          totalCount: 0,
          successCount: 0,
          failCount: 0
        };
      }

      console.log(`获取到 ${records.length} 条待处理记录\n`);

      // 逐条处理
      const results = [];
      for (const record of records) {
        const result = await this.processSingleRecord(record);
        results.push(result);
      }

      // 统计结果
      const successCount = results.filter(r => r.success).length;
      const failCount = results.filter(r => !r.success).length;

      console.log('\n========== 批量处理完成 ==========');
      console.log(`总数: ${records.length}`);
      console.log(`成功: ${successCount}`);
      console.log(`失败: ${failCount}`);
      console.log('==================================\n');

      return {
        success: true,
        totalCount: records.length,
        successCount,
        failCount,
        details: results
      };
    } catch (error) {
      console.error('批量处理失败:', error.message);
      throw error;
    }
  }

  /**
   * 删除待处理记录
   * @param {number} id - 记录ID
   * @returns {Promise<Object>} - 删除结果
   */
  async deleteRecord(id) {
    try {
      console.log(`删除待处理记录: ID ${id}`);

      // 检查记录是否存在且状态为pending
      const [rows] = await pool.execute(
        'SELECT * FROM raw_weapons WHERE id = ?',
        [id]
      );

      if (rows.length === 0) {
        return {
          success: false,
          message: '记录不存在'
        };
      }

      const record = rows[0];

      // 只允许删除待处理的记录
      if (record.process_status !== 'pending') {
        return {
          success: false,
          message: `无法删除：该记录状态为 ${record.process_status}，只能删除待处理的记录`
        };
      }

      // 执行删除
      await pool.execute(
        'DELETE FROM raw_weapons WHERE id = ?',
        [id]
      );

      console.log(`✓ 记录删除成功: ${record.name} (ID: ${id})`);

      return {
        success: true,
        message: '删除成功',
        name: record.name,
        id: id
      };
    } catch (error) {
      console.error('删除记录失败:', error.message);
      throw error;
    }
  }

  /**
   * 获取处理统计信息
   * @returns {Promise<Object>} - 统计信息
   */
  async getProcessStatistics() {
    try {
      // 获取各状态的数量
      const [rows] = await pool.execute(`
        SELECT 
          COUNT(*) as total,
          SUM(CASE WHEN process_status = 'pending' THEN 1 ELSE 0 END) as pending,
          SUM(CASE WHEN process_status = 'completed' THEN 1 ELSE 0 END) as completed,
          SUM(CASE WHEN process_status = 'failed' THEN 1 ELSE 0 END) as failed,
          SUM(CASE WHEN process_status = 'processing' THEN 1 ELSE 0 END) as processing
        FROM raw_weapons
      `);

      const stats = rows[0];
      const total = parseInt(stats.total) || 0;
      const pending = parseInt(stats.pending) || 0;
      const completed = parseInt(stats.completed) || 0;
      const failed = parseInt(stats.failed) || 0;
      const processing = parseInt(stats.processing) || 0;

      // 已处理 = 已完成 + 失败
      const processed = completed + failed;
      
      // 计算完成百分比
      const percentage = total > 0 ? Math.round((processed / total) * 100) : 0;

      return {
        total,
        pending,
        completed,
        failed,
        processing,
        processed,
        percentage
      };
    } catch (error) {
      console.error('获取处理统计失败:', error.message);
      throw error;
    }
  }
}

module.exports = new WeaponService();

